const express = require('express')
const axios = require('axios')
const cros = require('cors')
const { baseUrl } = require('./baseUrl')
const req = require('express/lib/request')
const app = express()
app.use(express.json())
// 配置跨域
app.use(cros())
app.all(/./, async (req, res) => {
  axios.interceptors.request.use((config) => {
    // 域名头设置
    config.baseURL = baseUrl
    // 读取代理的请求头token
    if (req.headers.token !== undefined) {
      config.headers.TOKEN = req.headers.token
    }
    return config
  })
  await axios({
    method: req.method,
    url: req.path,
    params: req.query,
    data: req.body
  }).then(success => {
    // const status = JSON.parse(JSON.stringify(success)).status
    const { data } = success
    // console.log(req.headers);
    res.status(success.status).json({
      ...data
    })
  }).catch(err => {
    const status = JSON.parse(JSON.stringify(err)).status
    // console.log(err);
    res.status(status).json({
      message: '请求错误!',
      error: err
    })
  })
})
app.listen(9362, () => {
  console.log('--port 9362')
})